class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        left=right=0
        maxv=minv=nums[0]
        result=1
        class BiQueue:
            def __init__(self):
                self.bigs=[]
                self.smalls=[] 

            def push(self,val):
                if not self.smalls or (self.bigs and val>=self.bigs[-1]):
                    i=len(self.bigs)-1
                    while i>=0 and val>self.bigs[i]:
                        self.smalls.append(self.bigs.pop())
                        i-=1
                    self.bigs.append(val)
                elif not self.bigs or (self.smalls and val<self.smalls[-1]):
                    i=len(self.smalls)-1
                    while i>=0 and val<self.smalls[i]:
                        self.bigs.append(self.smalls.pop())
                        i-=1
                    self.smalls.append(val)
                else:
                    self.bigs.append(val)
            
            def remove(self,val):
                if not self.bigs or val<self.bigs[-1]:
                    i=len(self.smalls)-1
                    while i>=0 and val!=self.smalls[i]:
                        self.bigs.append(self.smalls.pop())
                        i-=1
                    self.smalls.pop()
                else:
                    i=len(self.bigs)-1
                    while i>=0 and val!=self.bigs[i]:
                        self.smalls.append(self.bigs.pop())
                        i-=1
                    self.bigs.pop()
            
            def getLen(self):
                if not self.bigs:
                    return self.smalls[-1]-self.smalls[0]
                elif not self.smalls:
                    return self.bigs[0]-self.bigs[-1]
                else:
                    return self.bigs[0]-self.smalls[0]

            def printQueue(self):
                print(self.bigs,self.smalls)    
                
        queue=BiQueue()
        while right<len(nums):
            queue.push(nums[right])
            if queue.getLen()>limit:
                if right-left>result:
                    result=right-left
                while queue.getLen()>limit:
                    queue.remove(nums[left])
                    left+=1
            right+=1
            #queue.printQueue()
        if right-left>result:
            result=right-left
        return result


'''
超时
'''

from sortedcontainers import SortedList

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        s = SortedList()
        n = len(nums)
        left = right = ret = 0

        while right < n:
            s.add(nums[right])
            while s[-1] - s[0] > limit:
                s.remove(nums[left])
                left += 1
            ret = max(ret, right - left + 1)
            right += 1
        
        return ret